//
//  main.m
//  MethodSwizzling
//
//  Created by cygarm on 15/11/16.
//  Copyright © 2015年 cygarm. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <objc/runtime.h>
#import "NSArray+Swizzle.h"
#import "extobjc.h"


int main(int argc, const char * argv[]) {
	@autoreleasepool {
		Class class = [NSArray class];
		SEL origin_selector = @selector(lastObject);
		SEL my_selector = @selector(myLastObject);
		Method origin_method = class_getInstanceMethod(class, origin_selector);
		Method my_method = class_getInstanceMethod(class, my_selector);

		BOOL success = class_addMethod(class, origin_selector, method_getImplementation(my_method), method_getTypeEncoding(my_method));
		if (success) {
			//主类本身没有实现该方法,继承父类的实现
			//上面class_addMethod已经把my_method关联至主类实现,这里再把继承自父类的实现交换至my_selector
			class_replaceMethod(class, my_selector, method_getImplementation(origin_method), method_getTypeEncoding(origin_method));
		} else {
			//主类本身有实现该方法,直接调换两个方法的实现
			method_exchangeImplementations(origin_method, my_method);
		}
		
		
		NSArray *array = @[@"1", @"2", @"3"];
		NSString *lastObject = [array lastObject];
		NSLog(@"lastObject = %@", lastObject);
	}
	return 0;
}
